import type { FC } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import {
  Button, Modal,
  Image, message, Upload,
  Form,
  Card, Tooltip, Row, Col
} from 'antd';
import { useRequest } from '@umijs/max';
import {
  queryShortMediaList, queryShortMediaVote, queryShortKeyframes,
  addShortKeyframes, editShortKeyframes, delShortKeyframes,
  queryShortKeyframesList
} from '../service';
import { PlusOutlined, HeartTwoTone, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import Commen from './Commen/index'
import useStyles from '../style.style';


type OperationModalProps = {
  open: boolean;
  current: any;
  onDone: () => void;
  onSubmit: (values: any, type: boolean) => void;
  children?: React.ReactNode;
};

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const OperationModal: FC<OperationModalProps> = (props) => {
  const { styles } = useStyles()
  const formRef = useRef<ProFormInstance>(null);
  const { open, current, onDone, onSubmit } = props;
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [videoList, setVideoList] = useState<UploadFile[]>([]);
  const [filekeyList, setFilekeyList] = useState<any>({});
  const [currentEditingImages, setCurrentEditingImages] = useState<UploadFile[]>([]);
  const [isEditingMode, setIsEditingMode] = useState(false);
  const [currentEditingKeyframe, setCurrentEditingKeyframe] = useState<any>(null);
  const [keyframeViewMode, setKeyframeViewMode] = useState<'display' | 'edit'>('display');

  const { run: queryMediaList } = useRequest(queryShortMediaList, {
    manual: true,
    onSuccess: (data, params) => {
      // 获取media资源 接口成功
      setFileList(data?.map((e: any) => ({
        uid: e?.id,
        name: e?.filename,
        size: e?.file_size,
        url: e?.file_path,
      })))
    },
  });

  const { data: keyframesData, run: keyframesRun } = useRequest(queryShortKeyframes, {
    manual: true,
  });
  const { run: keyframesMediaRun } = useRequest(queryShortKeyframesList, {
    manual: true,
  });

  const { run: addKeyframesRun } = useRequest(addShortKeyframes, {
    manual: true,
  });
  const { run: editKeyframesRun } = useRequest(editShortKeyframes, {
    manual: true,
  });
  const { run: delKeyframesRun } = useRequest(delShortKeyframes, {
    manual: true,
  });

  const { run: queryMediaVote } = useRequest(queryShortMediaVote, {
    manual: true,
    onSuccess: (data, params) => {
      // 投票media资源 接口成功
    },
  });

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const onSetCurImg = (file: any) => {
    queryMediaVote(file?.id)
  }

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  }
  const handleVideoChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setVideoList(newFileList);
  }
  const beforeUploadVideo = (file: FileType) => {
    const sizeInMB = file.size / 1024 / 1024;
    const maxSizeMB = 100; // 调整允许的视频大小上限
    if (sizeInMB > maxSizeMB) {
      message.error(`视频过大（${sizeInMB.toFixed(1)}MB），请上传不超过 ${maxSizeMB}MB 的文件`);
      return Upload.LIST_IGNORE;
    }
    return true;
  }
  // const handleKeyChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
  //   setFilekeyList(newFileList);
  // }

  const addKeyFrame = () => {
    const data = {
      shot_id: current?.id,
      timestamp: '',
      image_prompt_chinese: '',
      image_prompt_english: '',
    }
    addKeyframesRun(data).then((e) => {
      if (e?.id) {
        message.success('添加成功')
        // 进入编辑态
        setKeyframeViewMode('edit')
        setIsEditingMode(true)
        setCurrentEditingKeyframe(e)
        keyframesRun(current?.id)
      } else {
        message.error('添加失败')
      }
    })
  }

  const editKeyFrame = (keyframe: any) => {
    // 从表单中获取当前编辑的内容
    const formValues = formRef.current?.getFieldsValue();
    const keyframeIndex = keyframesData?.findIndex((k: any) => k.id === keyframe.id) || 0;
    const imagePromptChinese = formValues?.[`image_prompt_chinese_${keyframeIndex}`] || '';

    editKeyframesRun({ ...keyframe, keyframe_id: keyframe?.id, image_prompt_chinese: imagePromptChinese }).then(e => {
      if (e?.id) {
        message.success('修改成功')
        // 重新获取关键帧数据，但保持当前的图片数据
        keyframesRun(current?.id).then(() => {
          // 确保图片数据不被覆盖
          if (currentEditingKeyframe?.id && filekeyList[currentEditingKeyframe.id]) {
            console.log('保持当前编辑关键帧的图片数据:', filekeyList[currentEditingKeyframe.id]);
          }
        });
        setKeyframeViewMode('display')
        setIsEditingMode(false)
        setCurrentEditingKeyframe(null)
      } else {
        message.error('修改失败')
      }
    })
  }

  // 关键帧图片上传处理函数
  const handleKeyframeUploadChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
    console.log('关键帧图片上传状态变化:', file?.status, file?.name);
    
    // 更新当前编辑关键帧的图片列表
    setCurrentEditingImages(newFileList);

    // 处理上传状态
    if (file?.status === 'done') {
      console.log('关键帧图片上传成功:', file);
      message.success('图片上传成功');
      
      // 重新获取关键帧图片数据并立即更新
      if (currentEditingKeyframe?.id) {
        keyframesMediaRun(currentEditingKeyframe.id).then(res => {
          console.log('重新获取关键帧图片数据:', res);
          const newImages = res?.map((e: any) => ({
            uid: e?.id,
            name: e?.filename,
            size: e?.file_size,
            url: e?.file_path,
          })) || [];
          
          // 更新两个状态
          setCurrentEditingImages(newImages);
          setFilekeyList((prev: any) => ({
            ...prev,
            [currentEditingKeyframe.id]: newImages
          }));
        }).catch(error => {
          console.error('获取关键帧图片数据失败:', error);
        });
      }
    } else if (file?.status === 'error') {
      console.error('关键帧图片上传失败:', file);
      message.error(`图片上传失败: ${file?.error?.message || '未知错误'}`);
    } else if (file?.status === 'uploading') {
      console.log('关键帧图片上传中:', file.name, file.percent + '%');
    }
  };

  const handleEditKeyframe = (keyframe: any) => {
    setKeyframeViewMode('edit')
    setIsEditingMode(true)
    setCurrentEditingKeyframe(keyframe)

    // 设置表单初始值
    const keyframeIndex = keyframesData?.findIndex((k: any) => k.id === keyframe.id) || 0;
    formRef.current?.setFieldsValue({
      [`image_prompt_chinese_${keyframeIndex}`]: keyframe.image_prompt_chinese || ''
    });

    // 强制刷新当前关键帧的图片数据，确保显示最新状态
    console.log('进入编辑模式，刷新关键帧图片数据:', keyframe.id);
    keyframesMediaRun(keyframe.id).then(res => {
      console.log('编辑模式下获取关键帧图片数据:', keyframe.id, res);
      const newImages = res?.map((e: any) => ({
        uid: e?.id,
        name: e?.filename,
        size: e?.file_size,
        url: e?.file_path,
      })) || [];
      
      // 更新两个状态
      setCurrentEditingImages(newImages);
      setFilekeyList((prev: any) => ({
        ...prev,
        [keyframe.id]: newImages
      }));
    }).catch(error => {
      console.error('编辑模式下获取关键帧图片数据失败:', keyframe.id, error);
    });
  }

  const handleCancelEdit = () => {
    setKeyframeViewMode('display')
    setIsEditingMode(false)
    setCurrentEditingKeyframe(null)
    setCurrentEditingImages([])
  }

  const handleConfirmEdit = () => {
    if (currentEditingKeyframe) {
      editKeyFrame(currentEditingKeyframe)
    }
  }

  const handleDeleteKeyframe = () => {
    if (currentEditingKeyframe) {
      Modal.confirm({
        title: '是否确认删除？',
        content: '删除后将无法恢复，请确认是否继续？',
        onOk: () => {
          delKeyframesRun(currentEditingKeyframe?.id).then(e => {
            if (e?.id) {
              message.success('删除成功')
              keyframesRun(current?.id)
              setKeyframeViewMode('display')
              setIsEditingMode(false)
              setCurrentEditingKeyframe(null)
            } else {
              message.error('删除失败')
            }
          })
        }
      })
    }
  }


  const uploadButton = (
    <button style={{ border: 0, background: 'none', width: '100%', height: '100%' }} type="button">
      <PlusOutlined style={{ fontSize: '24px', color: '#999' }} />
      <div style={{ marginTop: 8, color: '#999' }}>上传图片</div>
    </button>
  );

  // 新增关键帧Card组件
  const AddKeyframeCard = () => (
    <Col xs={24} sm={12} md={6} lg={6} style={{ marginBottom: 16 }}>
      <Card
        hoverable
        style={{
          height: 200,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: '2px dashed #d9d9d9',
          borderRadius: '8px',
          cursor: 'pointer',
          backgroundColor: '#fafafa'
        }}
        onClick={addKeyFrame}
      >
        <div style={{ textAlign: 'center', color: '#999' }}>
          <PlusOutlined style={{ fontSize: '32px', marginBottom: 8 }} />
          <div>新增关键帧</div>
        </div>
      </Card>
    </Col>
  );

  // 关键帧Card组件 - 展示态
  const KeyframeCard = ({ keyframe, index }: { keyframe: any, index: number }) => {
    const images = filekeyList?.[keyframe.id] || [];
    const firstImage = images[0];
    return (
      <Col xs={24} sm={12} md={6} lg={6} style={{ marginBottom: 16 }}>
        <Card
          hoverable
          style={{
            borderRadius: '8px',
            height: 200,
            cursor: 'pointer',
            transition: 'all 0.3s ease',
            border: '1px solid #f0f0f0'
          }}
          onClick={() => handleEditKeyframe(keyframe)}
          cover={
            firstImage ? (
              <div style={{ height: 120, overflow: 'hidden', borderRadius: '8px 8px 0 0' }}>
                <Image
                  src={firstImage.url}
                  alt={firstImage.name}
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  preview={false}
                />
              </div>
            ) : (
              <div style={{
                height: 120,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#f5f5f5',
                color: '#999',
                borderRadius: '8px 8px 0 0'
              }}>
                暂无图片
              </div>
            )
          }
        >
          <Card.Meta
            title={
              <div style={{ fontSize: '14px', fontWeight: 500 }}>
                关键帧{index + 1}
              </div>
            }
            description={
              <Tooltip title={keyframe.image_prompt_chinese || '暂无描述'}>
                <div style={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  fontSize: '12px',
                  color: '#666',
                  marginTop: 4
                }}>
                  {keyframe.image_prompt_chinese || '暂无描述'}
                </div>
              </Tooltip>
            }
          />
        </Card>
      </Col>
    );
  };

  // 编辑态表单组件
  const EditingForm = () => {
    if (!currentEditingKeyframe) return null;

    const keyframeIndex = keyframesData?.findIndex((k: any) => k.id === currentEditingKeyframe.id) || 0;

    return (
      <Card
        title={
          <div style={{ fontSize: '16px', fontWeight: 500 }}>
            关键帧{keyframeIndex + 1} - 编辑中
          </div>
        }
        style={{
          borderRadius: '8px',
          marginBottom: 16,
          border: '1px solid #d9d9d9',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}
        actions={[
          <Button key="cancel" onClick={handleCancelEdit}>
            取消
          </Button>,
          <Button key="delete" danger onClick={handleDeleteKeyframe}>
            删除
          </Button>,
          <Button key="confirm" type="primary" onClick={handleConfirmEdit}>
            确定
          </Button>
        ]}
      >
        <div style={{ marginBottom: 24 }}>
          <div style={{
            fontSize: '14px',
            fontWeight: 500,
            marginBottom: 8,
            color: '#fff'
          }}>
            生图提示词
          </div>
          <ProFormTextArea
            name={`image_prompt_chinese_${keyframeIndex}`}
            placeholder="请输入至少五个字符"
            style={{
              marginBottom: 16,
              minHeight: '80px'
            }}
            rows={3}
          />
        </div>
        <div style={{ marginBottom: 0 }}>
          <div style={{
            fontSize: '14px',
            fontWeight: 500,
            marginBottom: 8,
            color: 'rgba(0, 0, 0, 0.85)'
          }}>
            关键帧图片
          </div>
          <Upload
            action={`http://www.dtviptvott.com:14560/api/keyframes/${currentEditingKeyframe?.id}/media`}
            headers={{
              Authorization: `Bearer ${localStorage.getItem('token')}`
            }}
            listType="picture-card"
            name='files'
            showUploadList={{
              showDownloadIcon: true,
              downloadIcon: (file) => <HeartTwoTone twoToneColor={file?.uid ? '#555' : '#eb2f96'} />
            }}
            fileList={currentEditingImages}
            onPreview={handlePreview}
            onDownload={onSetCurImg}
            onChange={handleKeyframeUploadChange}
            beforeUpload={(file) => {
              console.log('准备上传关键帧图片:', file.name);
              return true;
            }}
          >
            {currentEditingImages?.length >= 10 ? null : uploadButton}
          </Upload>
        </div>
      </Card>
    );
  };

  useEffect(() => {
    if (current?.id && open) {
      queryMediaList(current?.id)
      keyframesRun(current?.id)
    }
    // 当模态框关闭时重置状态
    if (!open) {
      setKeyframeViewMode('display')
      setIsEditingMode(false)
      setCurrentEditingKeyframe(null)
      setCurrentEditingImages([])
    }
  }, [open, current])

  // 当关键帧数据变化时，预加载所有关键帧的图片数据
  useEffect(() => {
    if (keyframesData && keyframesData.length > 0) {
      keyframesData.forEach((keyframe: any) => {
        // 只有当该关键帧的图片数据不存在时才加载
        if (!filekeyList[keyframe.id]) {
          console.log('加载关键帧图片数据:', keyframe.id);
          keyframesMediaRun(keyframe.id).then(res => {
            console.log('获取到关键帧图片数据:', keyframe.id, res);
            setFilekeyList((prev: any) => ({
              ...prev,
              [keyframe.id]: res?.map((e: any) => ({
                uid: e?.id,
                name: e?.filename,
                size: e?.file_size,
                url: e?.file_path,
              })) || []
            }));
          }).catch(error => {
            console.error('加载关键帧图片数据失败:', keyframe.id, error);
          });
        } else {
          console.log('关键帧图片数据已存在，跳过加载:', keyframe.id);
        }
      })
    }
  }, [keyframesData])

  if (!open) {
    return null;
  }

  return (
    <ModalForm
      open={open}
      title={`${current ? '编辑' : '新增'}分镜`}
      className={styles.standardListForm}
      layout='horizontal'
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      initialValues={current}
      formRef={formRef}
      width={1080}
      modalProps={{
        onCancel: () => onDone(),
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        onSubmit(values, !!current);
      }}
    >
      <div
        className={styles.pageHeader}
      >
        <div className={styles.main}>
          <div style={{ flex: 1, overflow: 'auto', height: '500px' }}>
            <ProFormText
              name="duration"
              label="时长"
              rules={[
                {
                  required: true,
                  message: '请输入时长',
                },
              ]}
              placeholder="请输入时长"
            />
            <ProFormTextArea
              name="content"
              label="分镜内容"
              rules={[
                {
                  required: true,
                  message: '请输入描述',
                },
                {
                  message: '请输入至少五个字符的描述！',
                  min: 5,
                },
              ]}
              placeholder="请输入至少五个字符"
            />
            {
              current?.id ? (
                <>
                  <Form.Item
                    label="分镜图片"
                    style={{ marginBottom: 24 }}
                  >
                    <Upload
                      action={`http://www.dtviptvott.com:14560/api/shots/${current?.id}/media`}
                      headers={{
                        Authorization: `Bearer ${localStorage.getItem('token')}`
                      }}
                      name='files'
                      listType="picture-card"
                      fileList={fileList}
                      onPreview={handlePreview}
                      onChange={handleChange}
                    >
                      {fileList.length >= 10 ? null : uploadButton}
                    </Upload>
                  </Form.Item>

                  <Form.Item
                    label="分镜视频"
                    style={{ marginBottom: 24 }}
                  >
                    <Upload
                      action={`http://www.dtviptvott.com:14560/api/keyframes/${current?.id}/media`}
                      headers={{
                        Authorization: `Bearer ${localStorage.getItem('token')}`
                      }}
                      name='files'
                      accept="video/*"
                      listType="text"
                      multiple={false}
                      maxCount={1}
                      beforeUpload={beforeUploadVideo}
                      fileList={videoList}
                      onChange={handleVideoChange}
                    >
                      <Button type="dashed">
                        <PlusOutlined /> 上传视频
                      </Button>
                    </Upload>
                  </Form.Item>

                  <Form.Item
                    label="关键帧管理"
                    style={{ marginBottom: 24 }}
                  >
                    {keyframeViewMode === 'display' ? (
                      <Row gutter={[16, 16]}>
                        <AddKeyframeCard />
                        {keyframesData?.map((keyframe: any, index: number) => (
                          <KeyframeCard key={keyframe.id} keyframe={keyframe} index={index} />
                        ))}
                      </Row>
                    ) : (
                      <EditingForm />
                    )}
                  </Form.Item>
                </>
              ) : null
            }
          </div>
          {
            current?.id ? (
              <Commen current={current} />
            ) : null
          }
        </div>
        {previewImage && (
          <Image
            wrapperStyle={{ display: 'none' }}
            preview={{
              visible: previewOpen,
              onVisibleChange: (visible) => setPreviewOpen(visible),
              afterOpenChange: (visible) => !visible && setPreviewImage(''),
            }}
            src={previewImage}
          />
        )}
      </div>
    </ModalForm >
  );
};
export default OperationModal;
